package org.shan.hangtian.server.handler;

import com.mlnx.common.utils.MyLog;

import org.shan.hangtian.properties.HangtianProperties;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by amanda.shan on 2020/10/2.
 */
public class DataSaveHandle extends SimpleChannelInboundHandler<ByteBuf> {

    static MyLog log = MyLog.getLog(DataSaveHandle.class);

    private static OutputStream outputStream;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

        int len = msg.readableBytes();
        byte[] bytes = new byte[len];

        ByteBuf buf = msg.duplicate();
        ReferenceCountUtil.retain(buf);

        msg.readBytes(bytes);
        saveData(bytes);

        ctx.fireChannelRead(buf);
    }

    private static synchronized void saveData(byte[] bytes) throws IOException {

        log.debug("存储数据大小:{}", bytes.length);

        if (outputStream == null) {

//            File directory = new File("");
            File dir = new File(HangtianProperties.getInstance().getPath());
            dir.mkdirs();

            System.out.println(dir.getAbsolutePath());

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            File file = new File(dir.getAbsolutePath()
                    + File.separator + format.format(new Date()));
            outputStream = new FileOutputStream(file, true);
        }

        outputStream.write(bytes);
        outputStream.flush();
    }

    public static void main(String[] args) throws IOException {
        DataSaveHandle.saveData(new byte[10000]);
        DataSaveHandle.saveData(new byte[10000]);
        DataSaveHandle.saveData(new byte[10000]);
    }

}
